//****************************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
//****************************************************************************
using System;
using System.Configuration;
using System.Web.Configuration;
using System.Diagnostics.CodeAnalysis;
using Microsoft.FxCop.Sdk;

namespace Microsoft.FxCop.Rules.ASP.Security.Configuration
{
    sealed class AnonymousAccessIsEnabled : SystemWebConfigurationIntrospectionRule
    {

        #region *** Constructor ***
        public AnonymousAccessIsEnabled()
            : base(typeof(AnonymousAccessIsEnabled).Name)
        {
        }
        #endregion

        #region *** SystemWebConfigurationIntrospectionRule ***
        protected override ProblemCollection Check(SystemWebSectionGroup webConfig)
        {
            bool anonymousDeniedFound;

            if (webConfig == null)
                throw (new ArgumentNullException("webConfig"));

            //webConfig.Authorization.
            foreach (AuthorizationRule rule in webConfig.Authorization.Rules)
            {
                anonymousDeniedFound = false;

                switch (rule.Action)
                {
                    case AuthorizationRuleAction.Deny:
                        if (rule.Users.Count == 0)
                            AddProblem(rule.ElementInformation);
                        else
                        {
                            foreach (string user in rule.Users)
                            {
                                if (user == "?")
                                {
                                    anonymousDeniedFound = true;
                                    break;
                                }
                            }

                            if (!anonymousDeniedFound)
                            {
                                AddProblem(rule.ElementInformation);
                                return base.Problems;
                            }
                        }
                        break;
                    case AuthorizationRuleAction.Allow:
                        break;
                }
            }

            return base.Problems;
        }

        #endregion
    }
}